package com.reggie.handler;

import com.reggie.utils.Result;
import com.reggie.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */
//异常处理：所有加了RestController注解的方法，和所有Controller方法
@ControllerAdvice(annotations = {RestController.class, Controller.class})
//处理信息以json数据传到前端
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理添加时用户名存在异常
     * @param e
     * @return
     */
    //处理异常种类注解
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.error(e.getMessage());
        //具体的异常情况
        if (e.getMessage().contains("Duplicate entry")) {
            String[] split = e.getMessage().split(" ");
            String msg = split[2]+"已存在";
            return Result.error(msg);
        }
        return Result.error("未知错误");
    }

    @ExceptionHandler(Exception.class)
    public Result<String> otherExceptionHandler(Exception e) {
        if (!e.getMessage().contains("Duplicate entry")) {
            return Result.error("操作出现异常");
        }
        return Result.error("未知错误");
    }

    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public Result<String> exceptionHandler(CustomException e) {
        log.error(e.getMessage());
        return Result.error(e.getMessage());
    }
}
